#include <string.h>
#include <time.h>
#include <sys/socket.h>
#include <iostream>
#include <netinet/in.h>
#include <stdlib.h>
#include <error.h>
#include <stdio.h>

using namespace std;

static const int PORT = 50001;

int main()
{
	int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(listen_fd < 0)
	{
		cout<<"listen_fd:"<<listen_fd<<endl;
		exit(1);
	}

	struct sockaddr_in my_addr;
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(PORT);
	my_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int res = bind(listen_fd, (struct sockaddr*)&my_addr, sizeof(my_addr));
	if(res < 0)
	{
		cout<<"bind:"<<res<<endl;
		exit(1);
	}	
	res = listen(listen_fd, 5);
	if(res < 0)
	{
		cout<<"listen:"<<res<<endl;
		perror("listen");
		exit(1);
	}

	char buff[1024];
	while(true)
	{
		struct sockaddr_in remote_addr;
		socklen_t sin_size = sizeof(struct sockaddr_in);
		int new_sockfd = accept(listen_fd, (struct sockaddr*)&remote_addr, &sin_size);
		cout<<"new_sockfd"<<new_sockfd<<endl;
		cout<<new_sockfd<<endl;
		long bytes = 0;
		time_t start = time(NULL);
		while(true)
		{
			int rcvlen = recv(new_sockfd, buff, sizeof(buff), 0);
			if(rcvlen < 0 || rcvlen ==0)
			{
				close(new_sockfd);
				break;
			}
			bytes += rcvlen;
		}
		time_t end = time(NULL);
		cout<<difftime(end, start)<<":"<<bytes<<endl;
	}
	close(listen_fd);
}
